<template>
  <div class="profile-container">
    <h2>个人信息修改</h2>
    <form class="profile-form" @submit.prevent="submitForm">
      <div class="form-group">
        <label for="nickname">昵称:</label>
        <input
          id="nickname"
          v-model="userInfo.nickname"
          type="text"
          class="form-control"
        />
      </div>

      <div class="form-group">
        <label>头像:</label>
        <div class="avatar-section">
          <div v-if="userInfo.avatarPath" class="avatar-preview">
            <img :src="userInfo.avatarPath" alt="头像预览" class="avatar-image" />
          </div>
          <div class="upload-area">
            <input
              ref="fileInput"
              type="file"
              accept="image/*"
              @change="handleFileChange"
              class="file-input"
            />
            <button type="button" @click="triggerFileInput" class="upload-button">
              选择图片
            </button>
            <p class="upload-hint">支持 JPG、PNG 格式，大小不超过 2MB</p>
            </div>
        </div>
      </div>

      <div class="form-group">
        <label for="email">邮箱:</label>
        <input
          id="email"
          v-model="userInfo.email"
          type="email"
          class="form-control"
        />
      </div>

      <div class="form-group">
        <label for="phone">电话:</label>
        <input
          id="phone"
          v-model="userInfo.phone"
          type="tel"
          class="form-control"
        />
      </div>

      <div class="form-group">
        <label for="age">年龄:</label>
        <input
          id="age"
          v-model.number="userInfo.age"
          type="number"
          min="1"
          max="120"
          class="form-control"
        />
      </div>

      <div class="form-group">
        <label for="sex">性别:</label>
        <select id="sex" v-model="userInfo.sex" class="form-control">
          <option value="man">男</option>
          <option value="woman">女</option>
        </select>
      </div>

      <!-- 添加地址偏好设置 -->
      <div class="form-group">
        <label>地址偏好设置 (最多选择3个):</label>
        <div class="address-preferences">
          <div
            v-for="province in provinces"
            :key="province"
            class="address-item"
            :class="{ selected: selectedAddresses.includes(province) }"
            @click="toggleAddress(province)"
          >
            {{ province }}
          </div>
        </div>
        <div class="selected-addresses">
          已选择: {{ selectedAddresses.join(', ') || '无' }}
        </div>
      </div>

      <div class="form-actions">
        <button type="submit" class="submit-button">保存修改</button>
        <button
          v-if="userType === 'candidate'"
          type="button"
          @click="goToResume"
          class="resume-button"
        >
          修改在线简历
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import apiClient from '@/utils/api'
import axios from 'axios'
import router from '@/router'

export default {
  name: 'UserProfile',
  setup () {
    const userInfo = ref({
      userId: null,
      nickname: '',
      username: '',
      email: '',
      phone: '',
      age: null,
      sex: '',
      avatarPath: ''
    })

    // 地址集合
    const provinces = [
      '北京市', '上海市', '天津市', '重庆市',
      '河北省', '山西省', '辽宁省', '吉林省', '黑龙江省',
      '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省',
      '河南省', '湖北省', '湖南省', '广东省', '海南省',
      '四川省', '贵州省', '云南省', '陕西省', '甘肃省',
      '青海省', '台湾省',
      '内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区',
      '香港特别行政区', '澳门特别行政区'
    ]

    // 选中的地址
    const selectedAddresses = ref([])

    const fileInput = ref(null)
    const userType = ref('')

    const loadUserInfo = () => {
      const storedUserInfo = localStorage.getItem('userInfo')
      if (storedUserInfo) {
        const parsedUserInfo = JSON.parse(storedUserInfo)
        userInfo.value = {
          userId: parsedUserInfo.userId,
          nickname: parsedUserInfo.nickname,
          username: parsedUserInfo.username,
          email: parsedUserInfo.email,
          phone: parsedUserInfo.phone,
          age: parsedUserInfo.age,
          sex: parsedUserInfo.sex,
          avatarPath: parsedUserInfo.avatarPath
        }
        userType.value = parsedUserInfo.userType

        // 加载地址偏好设置
        if (parsedUserInfo.preferredAddresses) {
          selectedAddresses.value = parsedUserInfo.preferredAddresses
        }
      }
    }

    // 切换地址选择
    const toggleAddress = (province) => {
      const index = selectedAddresses.value.indexOf(province)
      if (index > -1) {
        // 如果已选择，则取消选择
        selectedAddresses.value.splice(index, 1)
      } else {
        // 如果未选择且未达到上限，则添加
        if (selectedAddresses.value.length < 3) {
          selectedAddresses.value.push(province)
        } else {
          alert('最多只能选择3个地址')
        }
      }
    }

    const handleFileChange = async (event) => {
      const file = event.target.files[0]
      if (!file) return

      // 验证文件类型和大小
      const validTypes = ['image/jpeg', 'image/png']
      const maxSize = 2 * 1024 * 1024 // 2MB

      if (!validTypes.includes(file.type)) {
        alert('头像图片只能是 JPG 或 PNG 格式!')
        return
      }

      if (file.size > maxSize) {
        alert('头像图片大小不能超过 2MB!')
        return
      }

      // 上传文件 - 修复后的代码
      try {
        const formData = new FormData()
        formData.append('file', file)

        // 创建一个新的 axios 实例用于文件上传，避免拦截器修改 Content-Type
        const token = localStorage.getItem('token')
        const uploadClient = axios.create({
          baseURL: 'http://localhost/api'
        })

        // 添加请求拦截器，只添加 token，不修改 Content-Type
        uploadClient.interceptors.request.use(
          config => {
            if (token) {
              config.headers.Token = token
            }
            return config
          },
          error => {
            return Promise.reject(error)
          }
        )

        const response = await uploadClient.post('/user/uploadAvatar', formData)

        if (response.data && response.data.data) {
          userInfo.value.avatarPath = response.data.data
          alert('头像上传成功')
        } else {
          alert('头像上传失败')
        }
      } catch (error) {
        console.error('上传失败:', error)
        alert('头像上传失败: ' + error.message)
      }
    }

    const triggerFileInput = () => {
      fileInput.value.click()
    }

    const submitForm = async () => {
      try {
        // 构造提交数据，只包含需要更新的字段
        const updateData = {
          userId: userInfo.value.userId,
          nickname: userInfo.value.nickname,
          email: userInfo.value.email,
          phone: userInfo.value.phone,
          age: userInfo.value.age,
          sex: userInfo.value.sex,
          avatarPath: userInfo.value.avatarPath,
          preferredAddresses: selectedAddresses.value // 添加地址偏好设置
        }

        const response = await apiClient.post('/user/updateUserInfo', updateData)

        if (response.data.code === '200') {
          alert('信息更新成功')
          // 更新localStorage中的用户信息
          const storedUserInfo = JSON.parse(localStorage.getItem('userInfo'))
          Object.assign(storedUserInfo, userInfo.value)
          // 添加地址偏好设置到localStorage
          storedUserInfo.preferredAddresses = selectedAddresses.value
          localStorage.setItem('userInfo', JSON.stringify(storedUserInfo))
        } else {
          alert(response.data.message || '更新失败')
        }
      } catch (error) {
        console.error('更新失败:', error)
        alert('更新失败: ' + error.message)
      }
    }

    const goToResume = () => {
      // 跳转到在线简历页面的逻辑
      router.push('/vitae/edit')
    }

    onMounted(() => {
      loadUserInfo()
    })

    return {
      userInfo,
      fileInput,
      userType,
      provinces,
      selectedAddresses,
      handleFileChange,
      triggerFileInput,
      submitForm,
      goToResume,
      toggleAddress
    }
  }
}
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  font-family: 'Arial', sans-serif;
}

h2 {
  color: #1890ff;
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
}

.profile-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
  font-size: 16px;
}

.form-control {
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-control:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.avatar-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.avatar-preview {
  flex: 0 0 auto;
}

.avatar-image {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #dcdfe6;
}

.upload-area {
  flex: 1;
  min-width: 200px;
}

.file-input {
  display: none;
}

.upload-button {
  padding: 10px 20px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.upload-button:hover {
  background-color: #40a9ff;
}

.upload-hint {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}

.form-actions {
  display: flex;
  gap: 15px;
  padding-top: 20px;
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
}

.submit-button, .resume-button {
  padding: 12px 30px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-button {
  background-color: #1890ff;
  color: white;
}

.submit-button:hover {
  background-color: #40a9ff;
}

.resume-button {
  background-color: #fff;
  color: #1890ff;
  border: 1px solid #1890ff;
}

.resume-button:hover {
  background-color: #e6f7ff;
}

/* 地址偏好设置样式 */
.address-preferences {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.address-item {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #1890ff;
}

.address-item.selected {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.selected-addresses {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 14px;
}

@media (max-width: 768px) {
  .profile-container {
    margin: 10px;
    padding: 20px;
  }

  .avatar-section {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-actions {
    flex-direction: column;
  }
}
</style>
